<!DOCTYPE html>
<html lang='en'>

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    .list {
      width: 200px;
      height: 150px;
      background-color: aqua;
      overflow: auto;
    }

    .news {
      height: 30px;
    }
  </style>
</head>

<body>
  <!-- 准备好容器 -->
  <div id="test"></div>

  <!--引入react核心库-->
  <script src="../react.js-18/react.development.js" type="text/javascript"></script>
  <!--引入react-dom，用于支持react操作DOM-->
  <script src="../react.js-18/react-dom.development.js" type="text/javascript"></script>
  <!--引入label，用于将jsx转为js-->
  <script src="../react.js-18/babel.min.js" type="text/javascript"></script>
  <!--引入prop-types，用于对组件标签属性的限制-->
  <script src="../react.js-18/prop-types.js" type="text/javascript"></script>

  <script type="text/babel">
    //1.创建组件>
    class NewsList extends React.Component {

      state = { newsArr: [] }

      componentDidMount() {
        setInterval(() => {
          //获取原状态
          const { newsArr } = this.state
          //模拟一条新闻
          const news = '新闻' + (newsArr.length + 1)
          //更新状态
          this.setState({ newsArr: [news, ...newsArr] })
        }, 1000)
      }

      // 在组件更新之前获取快照
      getSnapshotBeforeUpdate() {
        return this.refs.list.scrollHeight
      }

      // 组件更新后调用
      componentDidUpdate(prevProps, prevState, height) {
        this.refs.list.scrollTop += this.refs.list.scrollHeight - height
      }

      render() {
        return (
          <div>
            <div className="list" ref="list">
              {
                this.state.newsArr.map((n, index) => {
                  return <div key="index" className="news">{n}</div>
                })
              }
            </div>
          </div>
        )
      }
    }
    //2.渲染组件到页面
    ReactDOM.render(<NewsList />, document.getElementById('test'))
  </script>
</body>

</html>